package cn.ylz.ylmall.content.service.impl;

import cn.ylz.ylmall.account.security.CurrentPrincipal;
import cn.ylz.ylmall.common.ex.ServiceException;
import cn.ylz.ylmall.common.web.JsonResult;
import cn.ylz.ylmall.common.web.ServiceCode;
import cn.ylz.ylmall.content.dao.persist.repository.IContentRepository;
import cn.ylz.ylmall.content.dao.persist.repository.ILikeRepository;
import cn.ylz.ylmall.content.pojo.entity.Like;
import cn.ylz.ylmall.content.pojo.param.LikeAddNewParam;
import cn.ylz.ylmall.content.pojo.vo.CountVO;
import cn.ylz.ylmall.content.pojo.vo.LikeStandardVO;
import cn.ylz.ylmall.content.service.ILikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static cn.ylz.ylmall.common.web.ServiceCode.LIKE_CANCEL;
import static cn.ylz.ylmall.common.web.ServiceCode.LIKE_SUCCESS;

@Slf4j
@Service
public class LikeServiceImpl implements ILikeService {
    @Autowired
    private ILikeRepository iLikeRepository;

    @Override
    public JsonResult addNew(CurrentPrincipal currentPrincipal, LikeAddNewParam likeAddNewParam) {
        Like like = new Like();
        BeanUtils.copyProperties(likeAddNewParam,like);
        like.setUserId(currentPrincipal.getId());
        System.out.println("检测插入数据是否正确"+like);
        //查询是否已经点赞
        LikeStandardVO result = iLikeRepository.selectIsLike(currentPrincipal.getId(),likeAddNewParam.getContentId());

        if(result == null){
            int rows = iLikeRepository.insert(like);
            if(rows !=1){
                String message = "点赞失败,请重试";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        return JsonResult.ok(LIKE_SUCCESS);
        }
        else {
            int rows = iLikeRepository.delete(currentPrincipal.getId(),likeAddNewParam.getContentId());
            if(rows !=1){
                String message = "取消点赞失败,请重试";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
            return JsonResult.ok(LIKE_CANCEL);
        }
    }

    @Override
    public CountVO count(Long contentId) {
        log.debug("开始处理统计点赞数量");
        return iLikeRepository.count(contentId);
    }

    @Override
    public Boolean selectIsLike(Long id, Long contentId) {
        LikeStandardVO result = iLikeRepository.selectIsLike(id,contentId);
        if(result == null){
            return false;
        }
        else {
            return true;
        }
    }
}
